package com.mars.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mars.base.service.support.BaseService;
import com.mars.upms.dao.mapper.UpmsPermissionMapper;
import com.mars.upms.entity.UpmsPermission;
import com.mars.upms.rpc.api.UpmsPermissionService;

@Service
public class UpmsPermissionServiceImpl extends BaseService<UpmsPermission, Integer> implements UpmsPermissionService {
	
	@Autowired
	private UpmsPermissionMapper mapper ;

	@Override
	public List<UpmsPermission> selectRoot(UpmsPermission entity) {
		return this.mapper.selectRoot(entity);
	}

	@Override
	public List<UpmsPermission> selectChildren(Integer pid, Integer[] type) {
		return this.mapper.selectChildren(pid, type);
	}

	@Override
	public List<UpmsPermission> tree(UpmsPermission entity) {
		Integer[] type = null ;
		if(null != entity.getType()) {
			type = new Integer[]{entity.getType()} ;
		}
		List<UpmsPermission> list = new ArrayList<UpmsPermission>() ;
		
		List<UpmsPermission> selectRoot = this.selectRoot(entity) ;
		for (UpmsPermission permission : selectRoot) {
			list.add(recursive(permission, type)) ;
		}
		return list;
	}
	
	private UpmsPermission recursive(UpmsPermission permission, Integer[] type) {
		
		List<UpmsPermission> selectChildren = this.selectChildren(permission.getId(), type) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsPermission> children = new ArrayList<UpmsPermission>() ;
			
			for (UpmsPermission childPermission : selectChildren) {
				children.add(recursive(childPermission, type)) ;
			}
			
			permission.setChildren(children);
		}
		return permission ;
	}

}
